<template>
  <el-container style="border: 1px solid #eee">
    <el-aside width="300px" height="200%" >
      <el-tree style="font-size: 12px"
        :data="data"
        :props="props"
        node-key="attrid"
        default-expand-all
        :expand-on-click-node="false">
      <span class="custom-tree-node" slot-scope="{ node, data }">
        <span>{{ data.attrname }}</span>
        <span>
          <el-button v-if="data.attrrank == 'T'"
            style="float:right"
            type="text"
            size="mini"
            @click="() => append(data)">
            +
          </el-button>
        </span>
      </span>
      </el-tree>
    </el-aside>

    <el-container>
      <el-header style=" font-size: 12px" >
        <el-row>
        <el-col class="drag-select"  ref="dragSelect" :span="15">
          搜索
          <el-tag  style="font-size: 6px;margin-right:5px"
            v-for="item in items" 
            :key="item.key"
            :type="item.type?item.type:'info'"
            :closable="true"
            @click="openDailog(item)"
            @close="handleClose(item)"
            size="mini"
            >
            {{ item.attrname }}
          </el-tag>
        </el-col>
        <el-col  :span="9" style="float：right">
        <span >
         <span >
           <el-button-group >
            <el-button  style="margin-left:20px"  class="button-new-tag" size="mini" @click="handleInputConfirm('&')">&</el-button>
            <el-button  size="mini" @click="handleInputConfirm('|')">|</el-button>
            <el-button  size="mini" @click="handleInputConfirm('(')">(</el-button>
            <el-button  size="mini" @click="handleInputConfirm(')')">)</el-button>
            <el-button   style="margin-right:20px" size="mini" @click="truncate" icon="el-icon-delete"></el-button>
            <el-button  size="mini" @click="getComsumers" icon="el-icon-search" type="primary"></el-button>
            <el-button  type="success"  size="mini" @click="addConsumerGroup">创建客群</el-button>
          </el-button-group>
        </span>
        <!-- <el-button v-else class="button-new-tag" size="small" @click="showInput">+ New Tag</el-button> -->
       
          </span>
                   </el-col>
          </el-row>
      </el-header>

      <el-main>
        <span v-for="item,index in (options)" :key="index">
          <span v-if="!item.type" style="color:blue">{{item.attrname}}</span>
          <span v-if="item.type" style="color:green">&nbsp; &nbsp; {{item.attrname=='&'?'and':(item.attrname=='|'?'or':item.attrname)}}&nbsp; &nbsp; </span>

          <span v-if="!item.type" style="color:blue"> &nbsp; &nbsp;  {{item.logicalConnective}} &nbsp; &nbsp;</span>
          <span v-if="!item.type" style="color:red"> '{{item[item.fieldname]}}'</span>

        </span>
        <el-table :data="tableData" v-loading="tableLoading" height="500" >
          <el-table-column prop="client_name" label="姓名" width="140">
          </el-table-column>
          <el-table-column prop="client_age" label="年龄" width="120">
          </el-table-column>
          <el-table-column prop="client_gender" label="性别">
          </el-table-column>
          <el-table-column prop="client_phone" label="电话">
          </el-table-column>
          <el-table-column prop="channel_type" label="渠道">
          </el-table-column>
          <el-table-column prop="client_product" label="产品分析">
          </el-table-column>
          <el-table-column prop="last_datediff" label="最近一次投保时间">
          </el-table-column>
          <el-table-column prop="branch_code" label="机构">
          </el-table-column>
        </el-table>
        <el-row>
          <el-col :span="12"><el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="currentPage"
              :page-sizes="[10, 100, 200, 400]"
              :page-size="10"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total">
            </el-pagination></el-col>
          <el-col :span="12">
            <span style="float :right;margin-top:5px;font-size:13px" class="textStyle">
              <span>
                共覆盖客户数量：
              </span>
              <span style="font-size:24px;color:red" class="textStyle">
                {{total}}
              </span>
              <span >，本次查询耗时： </span>
              <span style="font-size:24px;color:red" class="textStyle">
                {{timeConsuming}}
                ms
              </span>
            </span>

          </el-col>
        </el-row>
        
            
          </el-main>
          </el-container>
          <el-dialog :title="'标签值'" :visible.sync="dailogVisible" >
          <el-form :model="form" ref="form" label-width="180px">
            <el-form-item :label="thisItem.attrname" >
              <el-row>
                <el-col :span="4">
                  <el-select placeholder="请选择..." v-model="form.logicalConnective" default-first-option> 
                    <el-option key="eq" label="eq" value="eq"></el-option>
                    <el-option key="like" label="like" value="like"></el-option>
                    <el-option key="in" label="in" value="in"></el-option>
                    <el-option key="neq" label="neq" value="neq"></el-option>
                  </el-select>
                </el-col>
                <el-col :span="20">
                  <el-input v-if="thisItem.valuetype == 'string' ||thisItem.valuetype == 'int'||thisItem.valuetype =='double'" v-model="form[thisItem.fieldname]" autocomplete="off"></el-input>
                  <el-select v-if="thisItem.valuetype == 'enum'" v-model="form[thisItem.fieldname]" placeholder="请选择...">
                      <el-option
                        v-for="item in labels"
                        :key="item.id"
                        :label="item.value"
                        :value="item.id">
                      </el-option>
                  </el-select>
                </el-col>
              </el-row>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="dailogVisible = false">取 消</el-button>
            <el-button type="primary" @click="onConfirm">确 定</el-button>
          </div>
      </el-dialog>
          <el-dialog :title="'创建客群'" :visible.sync="addConsumerGroupDailogVisible">
          <el-form :model="consumerGroup" ref="consumerGroup"  label-width="80px">
            <el-form-item label="客群名称" >
              <el-input v-model="consumerGroup.groupname" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="描述" >
              <el-input v-model="consumerGroup.description" autocomplete="off"></el-input>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="addConsumerGroupDailogVisible = false">取 消</el-button>
            <el-button type="primary" @click="onSubmit" v-loading="createLoading">确 定</el-button>
          </div>
      </el-dialog>
  </el-container>


 
</template>

<script>
  let id = 1000;
  import ElDragSelect from '@/components/DragSelect' // base on element-ui
  import Sortable from 'sortablejs'

  export default {
    components:{ElDragSelect
    },
    data() {
      return {
        timeConsuming:0,
        form:{},
        labels: [],
        options: [],
        items: [],
        props:{
          label: 'attrname',
          children: 'children',
          isLeaf: 'leaf'
        },
        data:[],
        inputVisible: false,
        dailogVisible: false,
        addConsumerGroupDailogVisible: false,
        inputValue: '',
        tableData:[],
        thisItem:{},
        consumerGroup:{},
        total:0,
        currentPage: 1,
        disabled:false,
        tableLoading:false,
        createLoading:false,
      }
    },
    mounted(){
      if(this.$route.params.args){
        this.items = JSON.parse(this.$route.params.args)
        this.options = JSON.parse(this.$route.params.args)
        this.disabled = true
      }
      this.getTree()
      this.setSort()
    },
    methods: {
       handleSizeChange(val) {
        console.log(`每页 ${val} 条`);
      },
      handleCurrentChange(val) {
        console.log(`当前页: ${val}`);
      },
      onSubmit(){
        this.consumerGroup.args = JSON.stringify(this.options)
        this.createLoading = true
        this.submit({
          url: '/customergroup/create' ,// 假地址 自行替换
          method: 'post',
          data:this.consumerGroup
        }).then(response => {
          this.createLoading = false
          console.log(response)
          this.labels = response.data
          this.$message.success('创建成功！')
          this.addConsumerGroupDailogVisible = false
          this.$router.push({path:'/dashboard'})
        }).catch(e=>{
          this.createLoading = false
        })
      },
      addConsumerGroup(){
        this.addConsumerGroupDailogVisible = true
      },
      onConfirm(){
        this.thisItem.logicalConnective = this.form.logicalConnective
        if(Array.isArray(this.form[this.thisItem.fieldname])){
          this.thisItem.values = this.form[this.thisItem.fieldname]
        }else{
          this.thisItem.values = []
          this.thisItem.values.push(this.form[this.thisItem.fieldname])
        }
        this.thisItem[this.thisItem.fieldname] =this.form[this.thisItem.fieldname]
        this.dailogVisible = false
      },
      openDailog(item){
        if(!item.attrid){
          return
        }
        this.submit({
          url: '/tagvalue/page', // 假地址 自行替换
          method: 'post',
          data:{model:{lv3:item.attrid}}
        }).then(response => {
          console.log(response)
          this.labels = response.data.records
        })
        this.thisItem = item
        console.log(this.items,this.options)
        this.dailogVisible = true
        this.form = JSON.parse(JSON.stringify(this.thisItem))
      },
      checkValues(){
        if(this.options.length==0){
          return false
        }
        if(this.options[0].attrname == '&'||this.options[0].attrname =='|'){
          return false
        }
        if(this.options[this.options.length-1].attrname == '&'||this.options[0].attrname =='|'){
          return false
        }
        if(!this.options[0].type&&((!this.options[0].logicalConnective) || (!this.options[0][this.options[0].fieldname] ))){
              return false
          }
        for (let index = 1; index < this.options.length; index++) {
          const element = this.options[index];
          const lastElement = this.options[index-1];
          if(element.attrname =='&'||element.attrname =='|'){
            if(lastElement.attrname =='&'||lastElement.attrname =='|'){
              return false
            }
          }
          if(element.attrname =='('||element.attrname ==')'){
            if(element.attrname =='('||element.attrname ==')'){
              return false
            }
          }
          console.log(element)
          if(!element.type&&((!element.logicalConnective) || (!element[element.fieldname] ))){
              return false
          }
        }
        return true
      },
      getComsumers(){
        if(!this.checkValues()){
          this.$message.warning('条件校验未通过')
          return 
        }
        this.tableLoading = true
        var sendDate = (new Date()).getTime();
        this.submit({
          url: '/tag/tagPage', // 假地址 自行替换
          method: 'post',
          data:this.options
        }).then(response => {
          var receiveDate = (new Date()).getTime();
          this.timeConsuming = receiveDate - sendDate;
          this.tableData = response.data.data
          this.total = response.data.total
          this.tableLoading = false
        }).catch(err=>{
          this.tableLoading = false
        })
      },
      setSort() {
        const el = this.$refs.dragSelect.$el
        this.sortable = Sortable.create(el, {
          ghostClass: 'sortable-ghost', // Class name for the drop placeholder,
          setData: function(dataTransfer) {
            dataTransfer.setData('Text', '')
            // to avoid Firefox bug
            // Detail see : https://github.com/RubaXa/Sortable/issues/1012
          },
          onEnd: evt => {
            const targetRow = this.options.splice(evt.oldIndex, 1)[0]
            this.options.splice(evt.newIndex, 0, targetRow)
            console.log(this.options)
            // this.getComsumers()
          }
        })
      },
      showInput(){
        this.inputVisible = true;

      },
      setData(dataTransfer) {
      // to avoid Firefox bug
      // Detail see : https://github.com/RubaXa/Sortable/issues/1012
      dataTransfer.setData('Text', '')
      },
      getTree(){
        this.submit({
          url: '/tag/tree', // 假地址 自行替换
          method: 'get'
        }).then(response => {
          console.log(response)
          this.data = response.data
        })
      },
      append(data) {
        data = JSON.parse(JSON.stringify(data))
        data.key = parseInt(Math.random()*(1000-1+1)+1,10)
        this.items.push(data);
        this.options.push(data);
      },
      handleClose(tag) {
        debugger
          this.items.splice(this.items.indexOf(tag), 1);
          this.options.splice(this.options.indexOf(tag), 1);
          // this.getComsumers()
        },
      truncate(){
        this.items = []
        this.options = []
      },
      handleInputConfirm(inputValue) {
        // let inputValue = this.inputValue;
        if (inputValue) {
          let obj = {key:parseInt(Math.random()*(1000-1+1)+1,10),attrname:inputValue,type:'success'}
          this.items.push(obj);
          this.options.push(obj);
          // this.getComsumers()
        }
        this.inputVisible = false;
        this.inputValue = '';
      }
    }
  }
</script>
<style lang="scss" scoped>
.textStyle {
    margin-right: 10px;
    font-weight: normal;
    color: #606266;
}
.drag-select {
  ::v-deep {
    .sortable-ghost {
      opacity: .8;
      color: #fff !important;
      background: #42b983 !important;
    }

    .el-tag {
      cursor: pointer;
    }
  }
}
  .el-header {
    background-color: #B3C0D1;
    color: #333;
    line-height: 60px;
  }

  .el-aside {
    color: #333;
  }
</style>

